package org.example.controller.sysuser;

import org.example.entity.SysUser;
import org.example.service.SysUserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class querySysUserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //接收表单的输入
        String username = req.getParameter("username");
        String userpwd = req.getParameter("password");

      //新建一个user实体，设定其用户名为输入的username
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
      //调用sysuser的实现类及其方法开展查询
        SysUserService sysUserService = new SysUserService();
        try {
            SysUser user = sysUserService.querySysUser(sysUser);
            //现在查看是否该用户是否存在，如果存在，则对比密码是否一致，如果不存在，则说明用户名输入错误
            System.out.println(user.getUserName());
            if(user.getUserName()!=null){
                if(userpwd.equals(user.getPassword())){
                    //重定向到main.jsp
                    resp.sendRedirect("main");
                    //将用户登录信息保存到session中，便于后续权限访问
                    HttpSession session = req.getSession();
                    session.setAttribute("username",username);
                }else{
                    //密码错误，重定向登录
                    req.setAttribute("errorMessage","用户密码输入错误");
                    //请求转发
                    req.getRequestDispatcher("/loginError.jsp").forward(req,resp);
                }
            }else{
                //用户不存在，重定向登录
                req.setAttribute("errorMessage","用户名不存在");
                //请求转发
                req.getRequestDispatcher("/loginError.jsp").forward(req,resp);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
